<template>
  <div class="map-content" id="mapContent">
  </div>
</template>

<script>
import * as echarts from 'echarts'
import zjAreaName from './mapSource/zjAreaName.js'
// import { getCurrentUser } from '@/api/admin/user'
import markerIcon from '..//bigScreen/mapIcon.png'
// import mapIconDefault from '../bigScreen/mapIconDefault.png'
import mapBG from '../bigScreen/mapBG.png'
export default {
  name: 'map-chart',
  props: {
    mapListObj: {
      type: Object,
      default: () => {
        return {}
      },
    },
    fieldTypeObj: {
      type: Object,
      default: () => {
        return {
          key: 'smIndexUnit',
          value: 'smIndexValue',
        }
      }
    },
  },
  data() {
    return {
      userInfo: null,
      preSelectMapIndex: null,
      myChart: null,
      currentCity: null,
      bgImageUrl: mapBG,
      moveCityName: null,
    }
  },
  methods: {
    selectRegion(chart, regionName, cityId = this.userInfo?.cityId, initBool = false) {

      if (this.preSelectMapIndex !== null) {
        chart.dispatchAction({
          type: 'unSelect',
          seriesIndex: 0,
          dataIndex: this.preSelectMapIndex,
        })
      }
      const data = chart.getOption().series[0].data
      const index = data.findIndex((item) => item.name === regionName)
      if (index !== -1) {
        chart.dispatchAction({
          type: 'select',
          seriesIndex: 0,
          dataIndex: index,
        })
        this.preSelectMapIndex = index
        if (initBool) {
          this.$emit('selectRegion', { regionName, cityId })
          this.initMap(cityId)
        }
      }
    },


    showCityDialog(cityName) {
      if (cityName === this.moveCityName) {
        return
      }
      this.moveCityName = cityName
      const option = this.myChart.getOption();
      const seriesData = option.series[0].data;
      const cityData = seriesData.find(item => item.name === cityName);
      if (!cityData) {
        console.error('未找到城市数据:', cityName);
        return;
      }

      try {
        // 清除旧弹窗
        const existingPopup = document.getElementById('popup');
        if (existingPopup) {
          this.moveCityName = ''
          existingPopup.remove();
          console.log('清除旧弹窗')
        }

        // 获取城市坐标
        const coord = cityData.value;
        const coordPoint = cityData.valuePoint
        const point = this.myChart.convertToPixel('geo', coord);
        console.log(cityName + '城市坐标:', coord, '像素位置:', point);
        const markPointOption = {
          series: [{
            markPoint: {
              symbol: `image://${markerIcon}`,
              symbolSize: [24, 24],
              symbolOffset: [0, 0],  // 图标向下偏移20像素
              data: [{
                name: cityName,
                coord: coordPoint,
                itemStyle: {
                  color: '#FF4500'
                },
                label: {
                  show: false
                }
              }]
            }
          }]
        }

        this.myChart.setOption(markPointOption)

        this.currentCity = cityName;
        if (point && point.length === 2) {
          // 创建新的弹窗
          const popup = this.createCityDialog(cityName, point);
          // 将弹窗插入到地图容器中
          const mapContent = document.getElementById('mapContent');
          if (mapContent) {
            mapContent.appendChild(popup);
            console.log('创建新弹窗')
          }
        }
      } catch (e) {
        console.error('显示弹框出错:', e);
      }
    },
    clearMarkers() {
      this.myChart?.clear();
      this.initMap();
      this.updateFontSize()

      const existingPopup = document.getElementById('popup');
      if (existingPopup) {
        existingPopup.remove();
        this.moveCityName = ''
      }

    },
    initUserDetail() {
      getCurrentUser().then(response => {
        this.userInfo = response.data.data
        this.$emit('userInfo', response.data.data)
        const validCityIds = []
        zjAreaName.forEach((value, key) => {
          validCityIds.push(key)
        })
        if (validCityIds.includes(this.userInfo.cityId)) {
          this.initMap()
          this.updateFontSize()
          window.addEventListener('resize', this.updateFontSize)
        } else {
          this.initMap()
        }
      }).catch(error => {
        console.error('获取用户信息失败:', error)
      })
    },
    // 添加防抖方法
    debounce(func, wait = 100) {
      let timeout;
      return function (...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
          func.apply(this, args);
        }, wait);
      };
    },
    initMap(selectCityId) {
      // if (!selectCityId && this.myChart) {
      //   this.myChart.dispose()
      // }
      // if (!this.userInfo?.cityId) { return }
      // let mapData = zjAreaName.get(selectCityId || this.userInfo?.cityId) || []
      // let mapJson = null
      // if (selectCityId) {
      //   mapJson = require(`./mapSource/${selectCityId}.json`)
      // } else if (this.userInfo?.cityId) {
      //   mapJson = require(`./mapSource/${this.userInfo?.cityId}.json`)
      // } else {
      //   mapJson = require(`./mapSource/0200.json`)
      // }
      // 



      const mapIconDefault = require('../bigScreen/mapIconDefault.png')
      let mapData = []
      let mapJson = require(`./mapSource/0200.json`)
      // this.myChart = echarts.init(this.$refs.myMap)
      this.myChart = echarts.init(document.getElementById('mapContent'))
      echarts.registerMap('myMap', mapJson)
      let option = {
        backgroundColor: "transparent",
        graphic: [],
        geo: [
          {
            type: "map",
            map: "myMap",
            z: 1,
            aspectScale: 1,
            zoom: 1,
            layoutCenter: ["50%", "50%"],
            layoutSize: "100%",
            show: true,
            roam: false,
            emphasis: {
              disabled: true
            },
            label: {
            },
            itemStyle: {
              normal: {
                borderColor: "rgba(255, 255, 255, 0.8)",
                borderWidth: 2,
                shadowColor: "#0986E6",
                shadowOffsetY: -1,
                shadowBlur: 10,
                areaColor: {
                  type: 'image',
                  image: this.bgImageUrl, // 使用背景图片
                  repeat: 'repeat',// 是否平铺，可以是 'repeat-x', 'repeat-y', 'no-repeat'
                  x: 15,
                  y: 10,
                },
                opacity: 1,
              },
            }
          },
        ],
        series: [
          {
            name: "浙江",
            type: "map",
            map: "myMap",
            aspectScale: 1,
            zoom: 1,
            showLegendSymbol: true,
            selectedMode: 'single',
            label: {
              normal: {
                show: true,
                textStyle: {
                  color: "#fff",
                  fontSize: '12px',
                  verticalAlign: 'bottom'  // 确保文字底部对齐
                }
              },
            },
            select: {
              itemStyle: {
                areaColor: {
                  type: 'radial',
                  x: 0.5,
                  y: 0.5,
                  r: 0.8,
                  colorStops: [{
                    offset: 0,
                    color: '#bd3d00'
                  }, {
                    offset: 1,
                    color: '#edba00'
                  }]
                },
                borderWidth: 1,
              },
              label: {
                show: true,
                formatter: '{b}',
                color: '#fff',
                fontSize: 18,
              }
            },
            emphasis: {
              disabled: true
            },
            itemStyle: {
              normal: {
                areaColor: {
                  type: "radial",  // 改为径向渐变
                  x: 0.5,          // 圆心x坐标（0-1，相对于元素宽度）
                  y: 0.5,          // 圆心y坐标（0-1，相对于元素高度）
                  r: 0.8,
                  colorStops: [{
                    offset: 0,
                    color: 'rgba(56,119,240,0.1)'
                  }, {
                    offset: 1,
                    color: 'rgba(56,119,240,0.1)'
                  }],
                  global: true,
                },
                borderColor: "#3877f0",
                borderWidth: 0.2,
              },
              emphasis: {
                show: false,
                color: "#44a8dc",
                areaColor: {
                  type: 'radial',
                  x: 0.5,
                  y: 0.5,
                  r: 0.8,
                  colorStops: [{
                    offset: 0,
                    color: '#bd3d00'
                  }, {
                    offset: 1,
                    color: '#edba00'
                  }]
                },
              },
            },
            layoutCenter: ["50%", "50%"],
            layoutSize: "100%",
            markPoint: {
              symbol: `image://${mapIconDefault}`,
              // symbol: `image://${require('@/views/riskBigScreen/bigScreen/mapIconDefault.png')}`,
              symbolSize: [24, 24],
              symbolOffset: [0, 10],  // 初始偏移设置
              itemStyle: {
                color: '#FF4500'
              },
              label: {
                show: false
              },
              data: mapData.map(item => ({
                name: item.name,
                coord: item.valuePoint,
                value: item.value
              })) || []
            },
            data: mapData
          }
        ],
      }
      const geoList = this.getMapOption()
      option.geo = option.geo.concat(geoList)
      this.myChart.setOption(option)

      // 修改鼠标移动事件监听，添加防抖
      // this.myChart.on('mousemove', this.debounce((params) => {
      //   if (!params.data) return;
      //   this.showCityDialog(params.data.name);
      //   // console.log('mousemove----', params.data.name)
      // }, 100));
      // 鼠标移入显示弹窗
      this.myChart.on('mouseover', (params) => {
        if (params.componentType === 'series' && params.seriesType === 'map') {
          this.showCityDialog(params.data.name)
        }
      })

      // 鼠标移出隐藏弹窗
      this.myChart.on('globalout', (params) => {
        // const existingPopup = document.getElementById('popup');
        // if (existingPopup) {
        //   existingPopup.remove();
        //   console.log('mouseout移除旧弹窗')
        //   this.moveCityName = ''
        // }
      })


      // 默认选中
      setTimeout(() => {
        let defaultCity = '杭州市'
        if (selectCityId) {
          // 下钻
          defaultCity = mapData?.find(item => item.cityId === selectCityId)?.name
          this.selectRegion(this.myChart, defaultCity)
          // this.showCityDialog(defaultCity)
        } else if (this.userInfo?.cityId !== '0201') {
          const cityData = mapData?.find(item => item.cityId === this.userInfo.cityId)
          defaultCity = cityData ? cityData.name : mapData[0]?.name
          this.selectRegion(this.myChart, defaultCity)
          // this.showCityDialog(defaultCity)
        }
      }, 500)
      // 点击事件
      this.myChart.off('click');
      this.myChart.on('click', (params) => {
        if (!params.data) return
        if (mapData.length > 1 && this.userInfo?.cityId === '0200') {
          this.selectRegion(this.myChart, params.data.name, params.data.cityId, true)
          this.showCityDialog(params.data.name)
        } else {
          const defaultCity = params?.data?.name
          this.selectRegion(this.myChart, defaultCity)
          this.showCityDialog(defaultCity)
        }
      })

      // 窗口大小变化
      const resizeHandler = () => {
        this.myChart.resize()
        if (this.currentCity) {
          this.showCityDialog(this.currentCity)
        }
      }
      window.addEventListener('resize', resizeHandler)

      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', resizeHandler)
      })
    },
    getMapOption() {
      const colorList = [
        'rgb(53, 114, 234)',  // 起始颜色
        'rgb(48, 103, 210)',
        'rgb(38, 81, 162)',
        'rgb(33, 70, 138)',
        'rgb(31, 62, 124)',
        'rgb(27, 52, 104)',
        'rgb(26, 48, 98)',
        'rgb(38, 81, 162)',
        'rgb(38, 81, 162)',
      ]
      const geoList = []
      for (let i = 0; i < colorList.length; i++) {
        const mapoption = {
          type: "map",
          map: "myMap",
          zoom: 1,
          aspectScale: 1,
          emphasis: { disabled: true },
          z: - i,
          roam: false,
          layoutCenter: [`${50 - i * 0.2}%`, `${50 + i * 0.5}%`],
          layoutSize: "100%",
          itemStyle: {
            normal: {
              areaColor: colorList[i - 1],
              borderWidth: 0
            }
          }
        }
        if (i === colorList.length - 1) {
          mapoption.itemStyle.normal.shadowColor = 'rgba(0,0,0,0.7)'
          mapoption.itemStyle.normal.shadowBlur = 100
        }
        geoList.push(mapoption)
      }
      return geoList
    },

    updateFontSize() {
      const fontSize = window.innerWidth * 0.009
      const option = this.myChart?.getOption()
      if (option) {
        option.series[0].label.textStyle.fontSize = fontSize + 'px'
        this.myChart.setOption(option)
      }
    },
    createCityDialog(cityName, position) {
      let arr = zjAreaName.get('0200') || [];
      let flagId = '';
      flagId = arr.find(item => { if (item.name == cityName) { return flagId = item.cityId; } })?.cityId || ''
      // const infoArr = this.mapListObj.find(item => item.org == flagId) || []
      const infoArr = this.mapListObj?.[flagId] || []
      // 创建弹窗的 HTML 内容
      const popup = document.createElement('div');
      popup.id = 'popup';

      // 设置弹窗样式
      popup.style.position = 'absolute';
      popup.style.left = `calc(${(position[0] / 1920) * 100}vw - 12vw)`  // 动态调整位置
      popup.style.top = `calc(${(position[1] / 1080) * 100}vh - 12vh)` // 动态调整位置
      popup.style.width = '13vw'; // 使用相对宽度（20% 的视口宽度）
      popup.style.height = '22vh'; // 使用相对高度（15% 的视口高度）
      popup.style.paddingLeft = '0.5vw'; // 使用相对单位
      popup.style.paddingRight = '0.5vw'; // 使用相对单位
      popup.style.paddingTop = '0.15vw'; // 使用相对单位
      popup.style.zIndex = 1000;

      // 添加背景图片
      popup.style.backgroundImage = `url(${require("../bigScreen/tkBG.png")})`; // 使用动态路径
      popup.style.backgroundSize = '100% 100%'; // 背景图片覆盖整个弹窗
      // 设置弹窗内容
      popup.innerHTML = `
        <div style="
          font-weight: bold;
          font-feature-settings: 'liga' off, 'clig' off;
          text-shadow: 0 2px 2px rgba(0, 38, 95, 0.3);
          font-family: 'Alimama ShuHeiTi', sans-serif;
          font-size: 1.6vh;
          font-weight: 700;
          background: linear-gradient(to bottom, #FFF 51.85%, #53B5FD 83.33%);
          -webkit-background-clip: text;
          background-clip: text;
          color: transparent;
          margin-bottom: 0.5vh;">
          ${cityName}
        </div>`;
      infoArr.forEach(e => {
        popup.innerHTML += `<div style="
          font-family: 'TCloudNumber', sans-serif;
          font-size: 1.4vh;
          font-weight: 400;
          color:#fff;
          letter-spacing: 0.5px;">
          <div style="display:flex;align-items:baseline;justify-content: space-between;">
            <div style="display:inline-block;width: 8vw;">${e.indexName}:</div>
            <div style="
            background: linear-gradient(124deg, #FD7700 16.08%, #F5CC00 86.44%);
            -webkit-background-clip: text;
            font-size:1.8vh;
            background-clip: text;
            display:inline-block;
            width: 4vw;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-left:5px;
            text-align: end;
            color: transparent;" title="${e?.[this.fieldTypeObj.value] || 0}${e?.[this.fieldTypeObj.key] || ''}">${e?.[this.fieldTypeObj.value] || 0} ${e?.[this.fieldTypeObj.key] || ''}</div>
          </div>`
      })
      popup.onclick = () => {
        popup.remove();
        console.log('点击弹窗')
      }
      return popup;
    },

  },
  created() {
    // this.initUserDetail()
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.updateFontSize)
    if (this.myChart) {
      this.myChart.dispose()
    }
  }
}
</script>

<style scoped>
#mapContent {
  /* position: relative; */
  width: 500px;
  height: 500px;
}
.map-content {
  border: 1px solid #fff;
}
</style>
